<template>
  <div class="pad-b-18">
    <header-bg></header-bg>
    <div class="detail-status line-h-1">
      <div>{{orderStatusDict[orderDetail.orderStatus]}}</div>
    </div>
    <div class="detail-address line-h-1">
      <div class="detail-post flex flex-between pad-t-15 pad-b-15" @click="queryExpressInfo" v-if="orderDetail.orderStatus === 2 || orderDetail.orderStatus === 3">
        <div class="flex flex-between">
          <img class="width-21 height-21" v-if="fileSpace" :src="fileSpace + '/images/express-car.png'" alt="">
          <div class="mar-l-16 flex-item" v-if="apartOrderIds.length === 1">
            <div class="line-1 font-15" v-if="expressTraces[0]">{{expressTraces[0].AcceptStation}}</div>
            <div class="line-1 font-15" v-else>暂无物流信息</div>
            <div class="mar-t-10 font-color-9 font-12" v-if="expressTraces[0]">{{expressTraces[0].AcceptTime}}</div>
          </div>
          <div class="mar-l-16 flex-item" v-else>
            <div class="line-1 font-15">物流派送中</div>
            <div class="mar-t-10 font-color-9 font-12">点击查看物流详情</div>
          </div>
        </div>
        <van-icon class="mar-l-20" name="arrow" color="#999999" size="24" />
      </div>
      <div class="flex flex-between pad-t-15 pad-b-18">
        <img class="width-21 height-21" v-if="fileSpace" :src="fileSpace + '/images/express-address.png'" alt="">
        <div class="flex-item mar-l-16">
          <div class="flex v-align-t flex-between">
            <div class="font-w font-20">
              <span>{{orderDetail.customerNickname}}</span>
              <span class="mar-l-5">{{orderDetail.customerPhone}}</span>
            </div>
            <div
              class="copy-btn mar-t-3"
              @click="$pt.setClipboardData({data: orderDetail.customerNickname + ' ' + orderDetail.customerPhone + ' ' + orderDetail.customerAddress})">
              复制
            </div>
          </div>
          <div class="line-2 width-224">{{orderDetail.customerFullAddress}}</div>
        </div>
      </div>
    </div>
    <div class="detail-goods pad-t-12">
      <div class="pad-l-15 pad-r-15 border-b">
        <div
          class="mar-b-18"
          v-for="(goods, goodsIndex) in orderGoodsList"
          :key="goodsIndex">
          <div class="flex mar-b-10 line-h-1">
            <div class="mar-r-10"><img :src="goods.goodsImageUrl" class="img-item" /></div>
            <div class="flex-item">
              <div class="item-bar-l">
                <div>
                  <div class="goods-title font-16 font-w mar-t-3">{{ goods.goodsTitle }}</div>
                  <div class="font-11 mar-t-6 font-color-9 flex flex-between" v-if="goods.skuDetail">
                    <span class="goods-prop">{{ goods.skuDetail }}</span>
                    <div class="font-15 align-r font-w font-color"> ×{{ goods.goodsNum }}</div>
                  </div>
                </div>
                <div class="flex v-align-c">
                  <div class="font-12 line-h-1" style="color: #F82A37;" v-if="goods.goodsPrice === '0.00'">免费寄样</div>
                  <div class="font-12 font-w flex-item v-align-c" v-else>
                    <span class="pad-t-4 pad-r-1">¥</span>
                    <span class="font-16">{{goods.goodsPrice}}</span>
                    <span class="font-12 font-normal font-color-9 pad-l-4">(观众价:¥{{goods.originalPrice}})</span>
                  </div>
                  <div v-if="!goods.skuDetail" class="font-15 align-r font-w font-color"> ×{{ goods.goodsNum }}</div>
                </div>
              </div>
              <!--  退款关闭: -3、4、3（数量全退完）
                  退款：-2、-1、3(数量未退完)、''
                  退款中：0、1、2 -->
              <div v-if="orderDetail.orderGoodsAmount * 1 > 0" class="flex">
                <div class="flex-item"></div>
                <template v-if="orderDetail.orderStatus !== -2 && orderDetail.orderStatus !== -1 && orderDetail.orderStatus !== 0 && orderDetail.orderStatus !== 4 && orderDetail.crossBorderOrderType !== 2">
                  <div @click.stop="linkToDetail(goods)"
                    v-if="(goods.afterSaleStatus===0 || goods.afterSaleStatus===1 || goods.afterSaleStatus===2)">
                    <div class="action-btn font-13 mar-t-5 mar-b-7">退款中</div>
                  </div>
                  <div class="action-btn font-13 mar-b-7"
                    v-else-if="goods.afterSaleStatus===-3 || goods.afterSaleStatus===4 || (goods.afterSaleStatus===3 && (goods.afterSaleGoodsNum===goods.goodsNum))">退款关闭</div>
                  <div v-else-if="orderDetail.afterSaleStatus !== 1 || (orderDetail.afterSaleStatus === 1 && orderDetail.deliveryType ===1)">
                    <div @click.stop="linkToApply(goods)"
                      v-if="orderStatusType !== '待发货' && (goods.afterSaleStatus===-2 || goods.afterSaleStatus===-1 || !goods.afterSaleStatus || (goods.afterSaleStatus===3 && (goods.afterSaleGoodsNum<goods.goodsNum)))" >
                      <div class="action-btn font-13 mar-t-5 mar-b-7">售后</div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
          <div v-if="getRoleType !== 2" class="flex v-align-b font-12 ratio-bar pad-b-5">
            <div class="flex-item pad-l-25">
              <div class="flex v-align-c pad-t-4">
                <div class="font-color-9 font-11 pad-r-8">主播佣金</div>
                <div class="font-12">{{ goods.anchorRatio ? goods.anchorRatio : '0.00' }}%</div>
              </div>
            </div>
          </div>
          <template v-else>
            <div class="flex v-align-b font-12 ratio-bar pad-t-3 pad-b-5">
              <div class="flex-item pad-l-25">
                <div>{{ goods.sampleTotalPartnerRatio ? goods.sampleTotalPartnerRatio : '0.00' }}%</div>
                <div class="font-color-9 font-11 mar-t--4">应获佣金</div>
              </div>
              <div class="flex-item">
                <div>{{ goods.samplePartnerRatio ? goods.samplePartnerRatio : '0.00' }}%</div>
                <div class="font-color-9 font-11 mar-t--4">实获佣金</div>
              </div>
              <div class="mar-r-25">
                <div>{{ goods.sampleAnchorRatio ? goods.sampleAnchorRatio : '0.00' }}%</div>
                <div class="font-color-9 font-11 mar-t--4">主播佣金</div>
              </div>
            </div>
            <div class="flex v-align-b font-12 ratio-bar pad-b-5 mar-t-6">
              <div class="flex-item pad-l-10">
                <div class="flex v-align-t pad-t-4">
                  <div class="font-11 pad-r-3">商品备注：</div>
                  <div class="font-12 flex-item">{{ goods.sellerWords }}</div>
                </div>
              </div>
            </div>
          </template>
        </div>
        <div class="pad-t-8 line-h-1">
          <div class="flex flex-between">
            <span>商品小计</span>
            <span class="font-12 font-w">￥<span class="font-16">{{ orderDetail.orderGoodsAmount }}</span></span>
          </div>
          <div class="flex flex-between mar-t-17">
            <span>运费</span>
            <span class="font-12 font-w">￥<span class="font-16">{{ orderDetail.freight }}</span></span>
          </div>
          <div class="flex flex-between mar-t-17 mar-b-20">
            <span>订单总价</span>
            <span class="font-12 font-w">￥<span class="font-16">{{ orderDetail.actualPrice }}</span></span>
          </div>
        </div>
      </div>
      <div class="flex flex-between pad-t-18 pad-b-18 pad-l-15 pad-r-15 line-h-1">
        <span>实付款</span>
        <span class="font-12 font-w" style="color:#F82A37;">￥<span class="font-16">{{orderDetail.actualPrice}}</span></span>
      </div>
    </div>
    <div class="detail-order line-h-1">
      <div class="flex flex-between font-12">
        <span><span class="font-color-9">订单编号：</span>{{orderDetail.orderNo}}</span>
        <div class="copy-btn" @click="$pt.setClipboardData({data: orderDetail.orderNo})">复制</div>
      </div>
      <div class="font-12 mar-t-10">
        <span><span class="font-color-9">下单时间：</span>{{orderDetail.createTime}}</span>
      </div>
      <div class="font-12 mar-t-13" v-if="orderDetail.orderStatus !== 0">
        <span><span class="font-color-9">支付时间：</span>{{orderDetail.payTime}}</span>
      </div>
      <div class="font-12 mar-t-13">
        <span><span class="font-color-9">订单状态：</span><span style="color:#FF0000;">{{orderStatusDict[orderDetail.orderStatus]}}</span></span>
      </div>
      <div class="font-12 mar-t-13" v-if="orderDetail.orderStatus === 2">
        <span><span class="font-color-9">发货时间：</span>{{orderDetail.deliveryTime}}</span>
      </div>
      <div class="font-12 mar-t-13" v-if="orderDetail.orderStatus === 3">
        <span><span class="font-color-9">收货时间：</span>{{orderDetail.receivedTime}}</span>
      </div>
    </div>
    <div class="detail-mark line-h-1">
      <span class="font-color-9">买家留言</span>
      <div class="mar-l-18 flex-item">{{orderDetail.customerComment || ''}}</div>
    </div>
    <div class="align-r line-h-1">
      <div v-if="orderDetail.orderStatus===0 || ((orderDetail.orderStatus === 1 || orderDetail.orderStatus === 20) && orderDetail.cancelFlag === 0) && orderDetail.customerMemberId === getCustomerId"
          class="order-btn mar-t-10 mar-r-10" :class="orderDetail.orderStatus == 20 ? 'disabled-order-btn2':''" @click="cancelOrder">取消订单</div>
      <!-- <div v-if="orderDetail.orderStatus===0"
          class="order-btn comfirm-btn mar-t-10 mar-r-10" @click="payOrder">去支付</div> -->
      <div class="pad-t-30"></div>
    </div>
  </div>
</template>
<script>
import HeaderBg from '@/components/headerBg'
import { getProjectOrder, payProjectOrder } from '@/api/distribution'
import { queryExpressByApartOrderId, getDict } from '@/api/common'
import { cancelOrder, checkCancelPaidOrder } from '@/api/personal'
export default {
  components: { HeaderBg },
  data() {
    return {
      orderGoodsList: [],
      orderDetail: {},
      apartOrderId: '',
      expressTraces: [],
      apartOrderIds: [], // 拆分订单id去重
      expressList: [], // 物流信息数组
      orderStatusDict: {},
      submitStatus: false,
      orderStatusType: ''
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
  },
  async onShow() {
    this.orderId = this.getCurrentPage().query.orderId
    await this.getOrderDic()
    this.getOrderDetail()
  },
  methods: {
    linkToDetail(sku) {
      sku.orderId = this.orderDetail.orderId
      let value = JSON.stringify(sku)
      this.$pt.navigateTo({url: `/pages/personal/order/refund-detail/main?sku=${value}`})
    },
    // 点击退货按钮
    linkToApply(val) {
      const {orderGoodsList} = this.orderDetail
      if (!val.apartOrderId) {
        // afterSaleStatus 商品售后状态  字段不存在时（undefined）是商品还没发起售后 -3:系统自动关闭 -2:顾客确认收货关闭  -1：已拒绝 0：待审核 1：待退货 2：退款中 3：已完成 4：已关闭
        if (this.orderDetail.crossBorderOrderType === 2 && this.orderDetail.orderStatus === 1) {
          // 跨境订单并且待发货，直接进入申请退款，整单退款
          let selectedOrderGoodsList = []
          let arr = []
          selectedOrderGoodsList = this.orderDetail.orderGoodsList
          selectedOrderGoodsList.forEach(item => {
            arr.push(item.orderGoodsId)
          })
          let orderGoodsIdStr = arr.join(',')
          this.$pt.navigateTo({url: `/pages/personal/order/refund-view/main?taxAmount=${this.orderDetail.taxAmount}&orderGoodsId=${orderGoodsIdStr}&sku=${JSON.stringify(selectedOrderGoodsList)}&orderId=${this.orderDetail.orderId}&storeGoods=1&orderStatusType=${this.orderStatusType}`})
          return
        }
        this.$pt.navigateTo({url: `/pages/personal/order/refund-goods/main?orderGoodsList=${JSON.stringify(orderGoodsList)}&orderId=${this.orderDetail.orderId}`})
      } else {
        this.$pt.navigateTo({url: `/pages/personal/order/refund-view/main?sku=${JSON.stringify(val)}&orderStatusType=${this.orderStatusType}&orderGoodsId=${val.orderGoodsId}`})
      }
    },
    payOrder() {
      if (this.submitStatus) {
        // 防重复提交
        return
      }
      this.submitStatus = true
      payProjectOrder(this.orderDetail.orderId).then(response => {
        if (response.isError) {
          this.submitStatus = false
          return
        }
        const that = this
        const payParams = response.data
        let resType = ''
        if (this.orderDetail.orderType === 30) {
          resType = '20'
        } else {
          resType = '10'
        }
        that.$pt.requestPayment({
          'timeStamp': payParams.timeStamp,
          'nonceStr': payParams.nonceStr,
          'package': payParams.package,
          'signType': payParams.signType,
          'paySign': payParams.paySign,
          'success': function(res) {
            that.submitStatus = false
            that.$pt.redirectTo({ url: '/pages/shop/result/main?successFlag=1&price=' + payParams.price +
                '&orderId=' + that.orderDetail.orderId + '&resType=' + resType })
          },
          'fail': function(res) {
            console.log(res)
            that.submitStatus = false
            that.$pt.navigateTo({ url: '/pages/shop/result/main?successFlag=0&price=' + payParams.price +
                '&orderId=' + that.orderDetail.orderId + '&resType=' + resType })
          }
        })
      })
    },
    cancelOrder() {
      // 取消订单事件
      // 订单里面都没有发货才可以取消订单，到订单取消页面
      // 否则提示联系卖家处理
      if (this.orderDetail.orderStatus === 20) return
      if (this.orderDetail.orderStatus === 0) {
        const that = this
        this.$pt.showModal({
          title: '温馨提示',
          content: '确认取消订单?',
          success: res => {
            if (res.confirm) {
              cancelOrder({orderId: that.orderDetail.orderId}).then(response => {
                if (response.isError) return
                that.$utils.showToast({ title: '取消成功' })
                that.orderDetail = {}
                that.getOrder()
              })
            }
          }
        })
      } else {
        checkCancelPaidOrder({orderId: this.orderDetail.orderId}).then(response => {
          if (response.isError) return
          this.$pt.navigateTo({url: '/pages/personal/order/cancel-order/main?memberId=' + this.orderDetail.memberId + '&orderId=' + this.orderDetail.orderId})
        })
      }
    },
    getOrderDic() {
      return new Promise((resolve, reject) => {
        getDict('UserOrderDTO.orderStatus').then((response) => {
          // console.log('订单状态字典')
          // console.log(response)
          if (response.isError) return
          this.orderStatusDict = response.data.orderStatus
          resolve(true)
        }).catch(() => {
        })
      })
    },
    // 查询物流信息
    queryExpressInfo() {
      if (this.apartOrderIds.length > 1) {
        this.$pt.navigateTo({ url: `/pages/personal/order/express-view/main?orderId=${this.orderId}` })
      } else {
        this.$pt.navigateTo({ url: `/pages/personal/order/express-detail/main?orderId=${this.orderId}` })
      }
    },
    getOrderDetail() {
      getProjectOrder(this.orderId).then(response => {
        if (response.isError) return
        this.orderDetail = response.data
        this.orderStatusType = this.orderStatusDict[this.orderDetail.orderStatus]
        this.orderGoodsList = response.data.orderGoodsList
        // 如果订单状态为 待收货/已收货  且 订单商品只有一个 则获取物流信息
        // 整理拆单ID，一个apartOrderId一个物流
        const apartOrderSet = new Set()
        this.orderGoodsList.forEach(item => {
          if (item.samplePartnerRatio && item.sampleAnchorRatio) {
            item.sampleLessRatio = ((item.samplePartnerRatio * 1) - (item.sampleAnchorRatio * 1)).toFixed(2)
            this.$set(item, 'sampleLessRatio', item.sampleLessRatio)
          }
          apartOrderSet.add(item.apartOrderId)
        })
        this.apartOrderIds = [...apartOrderSet]
        this.apartOrderIds.forEach(item => {
          this.getExpressDetail(item)
        })
      }).catch(() => {
      })
    },
    // 获取物流详情
    getExpressDetail(apartOrderId) {
      queryExpressByApartOrderId(apartOrderId).then(response => {
        if (response.isError) return
        if (this.apartOrderIds.length === 1) {
          this.expressTraces = response.data.Traces
        }
        if (response.data.trackingNo) {
          this.expressList.push(response.data)
        }
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang="less" scoped>
.ratio-bar{
  background: #f7f9fb;
  border-radius: 2px;
  // line-height: auto!important;
  .anchor-ratio-field{
    width: 63px;
    height: 20px;
    padding: 0 1px;
    box-sizing: border-box;
    border-radius: 3px;
    background: #e1e1e1;
    /deep/ .van-cell {
      margin: 0;
      border-top-left-radius: 3px;
      border-bottom-left-radius: 3px;
      border-top-right-radius: 0px;
      border-bottom-right-radius: 0px;
      padding: 0px 5px!important;
      height: 18px!important;
      min-height: 18px!important;
      line-height: 18px!important;
    }
    /deep/ .van-field__input{
      font-size: 11px!important;
      height: 18px!important;
      min-height: 18px!important;
      line-height: 18px!important;
    }
  }
  .per-tag{
    background: #e1e1e1;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
  }
}
.item-bar-l{
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 86px;
}
.action-btn {
  color: #666;
  background-color: #fff;
  height: 24px!important;
  line-height: 24px!important;
  padding: 0px 15px!important;
  border: 1px solid #e9e9e9;
  border-radius: 50px;
}
.order-btn {
  font-size: 13px;
  line-height: 1;
  display: inline-block;
  padding: 6px 12px;
  border-radius: 13.5px;
  color: #7427ff;
  background-color: #fff;
  border: #7427ff 1px solid !important;
  &.comfirm-btn{
    min-width: 52px;
    text-align: center;
    border: 1px solid #7427FF !important;
    color: #fff;
    background-color: #7427FF;
  }
}
.noraml-btnon{
  display: inline-block;
  color: #333333;
  border-radius: 100px;
  background-color: #fff;
  border: #c2c3c6 1px solid;
}
.disabled-order-btn2 {
  background: #dbdbdb !important;
  color: #fff !important;
  border: #dbdbdb 1px solid !important;
}
.line-h-1{
  line-height: 1;
}
.detail-status{
  font-size: 21px;
  font-weight: bold;
  color: white;
  margin-top: 23px;
  text-align: center;
}
.detail-address{
  background-color: white;
  border-radius: 5px;
  margin: 30px 10px 0;
  padding: 0 15px;
  .detail-post{
    border-bottom: 0.5px solid #E5E5E5;
  }
  .line-2{
    line-height: 1.4;
    max-height: 38px;
    color: #666;
    font-size: 15px;
    margin-top: 5px;
    height: unset;
  }
}
.detail-goods{
  margin: 10px 10px 0;
  border-radius: 5px;
  background-color: white;
  .goods-prop {
    box-sizing: border-box;
    height: 22px;
    line-height: 22px;
    padding: 0 7px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    word-break: break-word;
    background-color: #F7F9FB;
    border-radius: 2px;
    max-width: 150px;
  }
  .goods-title {
    height: 20px;
    line-height: 20px;
    overflow:hidden;
    text-overflow:ellipsis;
    display:-webkit-box;
    -webkit-line-clamp:1;
    -webkit-box-orient:vertical;
    word-break:break-word;
  }
  .img-item {
    width: 90px;
    height: 90px;
    border-radius: 5px;
  }
  .border-b{
    border-bottom: 0.5px solid #E5E5E5;
  }
}
.copy-btn{
  width: 43px;
  height: 19px;
  text-align: center;
  line-height: 19px;
  border-radius: 3px;
  font-size: 13px;
  border: 0.5px solid #CACACA;
}
.detail-order{
  background-color: white;
  border-radius: 5px;
  padding: 10px 15px 15px;
  margin: 10px 10px 0px;
}
.detail-mark{
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 13px 15px;
  background-color: white;
  border-radius: 5px;
  margin: 10px 10px 0px;
  line-height: 1.3;
}
.mar-t-46{
  margin-top: 46px;
}
</style>
